/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package mobcounter;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.SpinnerNumberModel;

/**
 *
 * @author Korn
 */
public class MainWindow extends javax.swing.JFrame implements MapPaintWidget.IPaintUpdate {

    private BufferedImage image;
    MapPaintWidget mapPaint;

    int betweenUpdate;

    /**
     * Creates new form MainWindow
     */
    public MainWindow() {
        this.betweenUpdate = 50;
        initComponents();
        mapPaint = new MapPaintWidget();
        chkAutoCal.setSelected(true);
        sclMap.setViewportView(mapPaint);
        mapPaint.setPreferredSize(new Dimension(500, 500));
        spnPP.setModel(new SpinnerNumberModel(Float.valueOf(5.0f), Float.valueOf(1.0f), null, Float.valueOf(0.5f)));
        mapPaint.SetBrushSize(sldSize.getValue());
        mapPaint.paintUpdate = this;

        String exepath = System.getProperty("user.dir");
        File file = new File(exepath+"/defaultmap.png");
        if (file.exists()) { 
            BufferedImage bitmp = null;
            try {
                bitmp = ImageIO.read(file);
            } catch (IOException ex) {
            }
            mapPaint.SetImage(bitmp);
            mapPaint.setPreferredSize(new Dimension(bitmp.getWidth(), bitmp.getHeight()));
            
        }
        tgPen.setSelected(true);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btOpen = new javax.swing.JButton();
        lbSSize = new javax.swing.JLabel();
        sldSize = new javax.swing.JSlider();
        txtSize = new javax.swing.JTextField();
        sclMap = new javax.swing.JScrollPane();
        btCal = new javax.swing.JButton();
        chkAutoCal = new javax.swing.JCheckBox();
        btClear = new javax.swing.JButton();
        lbPP = new javax.swing.JLabel();
        lbP = new javax.swing.JLabel();
        lbOutput = new javax.swing.JLabel();
        tgPen = new javax.swing.JToggleButton();
        tgErease = new javax.swing.JToggleButton();
        spnPP = new javax.swing.JSpinner();
        btSave = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        btOpen.setText("เปิดแผนที่");
        btOpen.setActionCommand("OnOpen");
        btOpen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btOpenActionPerformed(evt);
            }
        });

        lbSSize.setText("ขนาด");

        sldSize.setMajorTickSpacing(1);
        sldSize.setMinimum(1);
        sldSize.setMinorTickSpacing(1);
        sldSize.setValue(1);
        sldSize.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                sldSizeStateChanged(evt);
            }
        });

        txtSize.setText("1");

        btCal.setText("คำนวน");
        btCal.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btCalActionPerformed(evt);
            }
        });

        chkAutoCal.setText("คำนวนอัตโนมัต");

        btClear.setText("ลบทั้งหมด");
        btClear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btClearActionPerformed(evt);
            }
        });

        lbPP.setText("1 Pixel ต่อ");

        lbP.setText("คน");

        lbOutput.setText("ผลลัพท์");
        lbOutput.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        tgPen.setText("ปากกา");
        tgPen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tgPenActionPerformed(evt);
            }
        });

        tgErease.setText("ยางลบ");
        tgErease.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tgEreaseActionPerformed(evt);
            }
        });

        spnPP.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                spnPPStateChanged(evt);
            }
        });

        btSave.setText("บันทึก");
        btSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSaveActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(sclMap)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lbPP)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(spnPP)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(lbP)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(lbOutput, javax.swing.GroupLayout.PREFERRED_SIZE, 573, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(btOpen)
                                .addGap(15, 15, 15)
                                .addComponent(tgPen)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(tgErease, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(107, 107, 107)
                                .addComponent(lbSSize)
                                .addGap(6, 6, 6)
                                .addComponent(sldSize, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtSize, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(chkAutoCal)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(btCal)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(btClear, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btSave, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btClear)
                            .addComponent(txtSize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(chkAutoCal)
                            .addComponent(btCal))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btOpen)
                            .addComponent(lbSSize)
                            .addComponent(tgPen)
                            .addComponent(tgErease)))
                    .addComponent(sldSize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbPP)
                    .addComponent(lbOutput)
                    .addComponent(lbP)
                    .addComponent(spnPP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btSave))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(sclMap, javax.swing.GroupLayout.DEFAULT_SIZE, 303, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btOpenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btOpenActionPerformed
        // TODO add your handling code here:
        JFileChooser fc = new JFileChooser();
        int returnVal = fc.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            try {
                image = ImageIO.read(file);
            } catch (IOException ex) {
                Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
            }
            mapPaint.SetImage(image);
            mapPaint.setPreferredSize(new Dimension(image.getWidth(), image.getHeight()));
        } else {

        }
    }//GEN-LAST:event_btOpenActionPerformed

    private void sldSizeStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_sldSizeStateChanged
        // TODO add your handling code here:
        txtSize.setText(Integer.toString(sldSize.getValue()));
        mapPaint.SetBrushSize(sldSize.getValue());
    }//GEN-LAST:event_sldSizeStateChanged

    private void tgPenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tgPenActionPerformed
        // TODO add your handling code here:
        tgErease.setSelected(!tgPen.isSelected());
        if (tgPen.isSelected()) {
            mapPaint.SetPaintMode(new Color(1f, 0f, 0f, 1.0f));
        }
    }//GEN-LAST:event_tgPenActionPerformed

    private void tgEreaseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tgEreaseActionPerformed
        // TODO add your handling code here:
        tgPen.setSelected(!tgErease.isSelected());
        if (tgErease.isSelected()) {
            mapPaint.SetEreaseMode();
        }
    }//GEN-LAST:event_tgEreaseActionPerformed

    private void Cal() {
        if (!mapPaint.isReady()) {
            return;
        }

        float val = (float) spnPP.getValue();
        float fcount = mapPaint.Cal(val);
        lbOutput.setText("จำนวนคนโดยประมาณ : " + Float.toString(fcount));
    }

    private void btCalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCalActionPerformed
        // TODO add your handling code here:
        Cal();
    }//GEN-LAST:event_btCalActionPerformed

    private void spnPPStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spnPPStateChanged
        // TODO add your handling code here:
        float val = (float) spnPP.getValue();
        if (val < 1) {
            spnPP.setValue(1);
        }
        if (chkAutoCal.isSelected()) {
            Cal();
        }
    }//GEN-LAST:event_spnPPStateChanged

    private void btClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btClearActionPerformed
        // TODO add your handling code here:
        mapPaint.Clear();
    }//GEN-LAST:event_btClearActionPerformed

    private void btSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSaveActionPerformed
        // TODO add your handling code here:

        if (!mapPaint.isReady()) {
            return;
        }

        JFileChooser fc = new JFileChooser();
        int returnVal = fc.showSaveDialog(this);
        //fc.setSelectedFile(new File("united.jpg"));

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            String filePath = file.getAbsolutePath();
            if (!filePath.toLowerCase().endsWith(".png")) {
                file = new File(filePath + ".png");
            }

            try {
                ImageIO.write(
                        mapPaint.GetImage((float) spnPP.getValue()), "png", file);

            } catch (IOException ex) {
                ex.printStackTrace();
            }
        } else {

        }
    }//GEN-LAST:event_btSaveActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainWindow().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btCal;
    private javax.swing.JButton btClear;
    private javax.swing.JButton btOpen;
    private javax.swing.JButton btSave;
    private javax.swing.JCheckBox chkAutoCal;
    private javax.swing.JLabel lbOutput;
    private javax.swing.JLabel lbP;
    private javax.swing.JLabel lbPP;
    private javax.swing.JLabel lbSSize;
    private javax.swing.JScrollPane sclMap;
    private javax.swing.JSlider sldSize;
    private javax.swing.JSpinner spnPP;
    private javax.swing.JToggleButton tgErease;
    private javax.swing.JToggleButton tgPen;
    private javax.swing.JTextField txtSize;
    // End of variables declaration//GEN-END:variables

    @Override
    public void PaintUpdate(MapPaintWidget widget) {
        //if (chkAutoCal.isSelected()) {
        //    Cal();
        //}
    }

    @Override
    public void EndPaint(MapPaintWidget widget) {
        if (chkAutoCal.isSelected()) {
            Cal();
        }
    }
}
